<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">

      <el-form-item label="申请单ID" prop="id" v-if="false">
        <el-input
          v-model="queryParams.id"
          placeholder="申请单ID"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 110px;"
        />
      </el-form-item>
      <el-form-item label="申请单号" prop="appNo">
        <el-input
          v-model="queryParams.appNo"
          placeholder="申请单号"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 130px;"
        />
      </el-form-item>
      <el-form-item label="申请单位" prop="appUnit">
        <el-input
          v-model="queryParams.appUnit"
          placeholder="申请单位名称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 155px;"
        />
      </el-form-item>
      <el-form-item label="外协负责人" prop="outContact">
        <el-input
          v-model="queryParams.outContact"
          placeholder="外协负责人"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 120px;"
        />
      </el-form-item>

      <el-form-item label="外协单位" prop="outUnit">
        <el-input
          v-model="queryParams.outUnit"
          placeholder="外协单位名称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 130px;"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="outPhone">
        <el-input
          v-model="queryParams.outPhone"
          placeholder="外协负责人联系方式"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 150px;"
        />
      </el-form-item>
      <el-form-item label="申请日期" prop="appDate">
        <el-date-picker clearable
                        v-model="queryParams.appDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择申请日期"
                        style="width: 130px;"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['out:app:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleSubmissionForReview"
          v-hasPermi="['out:app:review']"
          :disabled="multiple_2"
        >送审</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:application:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:application:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" show-overflow-tooltip/>
      <el-table-column label="申请单ID" align="center" prop="id" width="120" v-if="true" show-overflow-tooltip/>
      <el-table-column label="申请单号" align="center" prop="appNo" width="150" show-overflow-tooltip/>
      <el-table-column label="申请单位" align="center" prop="appUnit" width="220" show-overflow-tooltip/>
      <el-table-column label="外协单位" align="center" prop="outUnit" width="250" show-overflow-tooltip/>
      <el-table-column label="进厂人数" align="center" prop="entryCount" width="100" show-overflow-tooltip/>
      <el-table-column label="外协负责人" align="center" prop="outContact" width="150" show-overflow-tooltip/>
      <el-table-column label="联系方式" align="center" prop="outPhone" width="150" show-overflow-tooltip/>
      <el-table-column label="状态" align="center" prop="status" show-overflow-tooltip>

        <template slot-scope="scope">
          <dict-tag :options="dict.type.out_app_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="right"
                       width="320">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['out:app:list']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['out:app:edit']"
            :disabled="![0, 3].includes(scope.row.status)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['out:app:delete']"
            :disabled="![0, 3].includes(scope.row.status)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleViewPerson(scope.row)"
            v-hasPermi="['out:app:person']"
          >查看人员</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleGenerateQRCode(scope.row)"

          >二维码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePagination"
    />

    <!-- 添加或修改临时通行证申请单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <!-- 顶部：申请单号（整行） -->
        <el-form-item label="申请单号" prop="appNo" label-width="120px">
          <el-input v-model="form.appNo" disabled style="width: 100%"/>
        </el-form-item>

        <!-- 中间：两列布局 -->
        <el-row :gutter="20">
          <!-- 第一列 -->
          <el-col :span="12">
            <el-form-item label="申请单位名称" prop="appUnit" label-width="120px" v-if="isDetailView" >
              <el-input v-model="form.appUnit" :disabled="isDetailView"/>
            </el-form-item>
            <el-form-item label="申请部门" prop="appUid" label-width="120px" v-if="!isDetailView">
              <treeselect v-model="form.appUid" :options="deptOptions" value-key="id" label-key="label" :show-count="true"  placeholder="请选择归属部门" />
            </el-form-item>
            <el-form-item label="申请人" prop="appPerson" label-width="120px">
              <el-input v-model="form.appPerson" :disabled="isDetailView"/>
            </el-form-item>

            <el-form-item label="申请日期" prop="appDate" label-width="120px">
              <el-date-picker
                v-model="form.appDate"
                type="date"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                :disabled="isDetailView"
              />
            </el-form-item>
          </el-col>

          <!-- 第二列 -->
          <el-col :span="12">
            <!-- 修改位置：将外协单位名称移到上方 -->
            <el-form-item label="外协单位名称" prop="outUnit" label-width="120px">
              <el-input v-model="form.outUnit" :disabled="true"/>
            </el-form-item>

            <el-form-item label="工作区域" prop="area" label-width="120px">
              <el-input v-model="form.area" :disabled="isDetailView"/>
            </el-form-item>

            <el-form-item label="外协负责人" prop="outContact" label-width="120px">
              <el-input v-model="form.outContact" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 底部区域 -->
        <el-row :gutter="20">
          <!-- 修改位置：将进厂人数移到下方左侧 -->
          <el-col :span="12">
            <el-form-item label="进厂人数" prop="entryCount" label-width="120px">
              <el-input-number
                v-model="form.entryCount"
                :min="1"
                :disabled="isDetailView"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="outPhone" label-width="120px">
              <el-input v-model="form.outPhone" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 工作内容（整行） -->
        <el-form-item label="工作内容" prop="content" label-width="120px">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="3"
            :disabled="isDetailView"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isDetailView" :loading="buttonLoading" type="primary" @click="submitForm">
          确 定
        </el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listApplication,
  getApplication,
  delApplication,
  generateAppNo,
  addApplication,
  updateApplication,
  getDeptName,
  updateApprovalStatus,
  deptTreeSelect,
  QRCode, sendOaToApproval, batchUpdateApprovalStatus
} from "@/api/outsourcing/application";
import  { getInfo } from "@/api/login";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import axios from "axios";



export default {
  name: "Application",
  components: {Treeselect},
  dicts: ['out_app_status'],
  props: {
    // 接收父组件传递的appId
    appId: {
      type: [String, Number],
      default: null
    },
    isTodo: {
      type: [Boolean, Number],
      default: false
    }
  },
  data() {
    return {
      // 是否为详情视图模式
      isDetailView: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //是否全是新建状态
      selectedAllNew: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      multiple_2: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 临时通行证申请单表格数据
      applicationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //流程id
      definitionId: '',
      deployId: '',
      _isTodo: 0,
      //部门选择
      deptOptions: undefined,
      // 查询参数
      queryParams: {
        id: null,
        pageNum: 1,
        pageSize: 10,
        appNo: undefined,
        appUid: undefined,
        appUnit: undefined,
        appPerson: undefined,
        entryCount: undefined,
        outContact: undefined,
        content: undefined,
        appDate: undefined,
        outUid: undefined,
        outUnit: undefined,
        area: undefined,
        outPhone: undefined,
        status: undefined,
        updateBy: undefined,
      },
      //部门
      deptQuery: {
        parentId: '',
        deptName: '',
        orderNum: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "申请单ID不能为空", trigger: "blur" }
        ],
        appNo: [
          { required: true, message: "申请单号不能为空", trigger: "blur" }
        ],
        appUid: [
          { required: true, message: "申请单位ID不能为空", trigger: "blur" }
        ],
        appUnit: [
          { required: true, message: "申请单位名称不能为空", trigger: "blur" }
        ],
        appPerson: [
          { required: true, message: "申请人不能为空", trigger: "blur" }
        ],
        entryCount: [
          { required: true, message: "进厂人数不能为空", trigger: "blur" }
        ],
        outUserName: [
          { required: true, message: "外协负责人账号不能为空", trigger: "blur" }
        ],
        outContact: [
          { required: true, message: "外协负责人不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "工作内容不能为空", trigger: "blur" }
        ],
        appDate: [
          { required: true, message: "申请日期不能为空", trigger: "blur" }
        ],
        outUid: [
          { required: true, message: "外协单位ID不能为空", trigger: "blur" }
        ],
        outUnit: [
          { required: true, message: "外协单位名称不能为空", trigger: "blur" }
        ],
        area: [
          { required: true, message: "工作区域不能为空", trigger: "blur" }
        ],
        outPhone: [
          { required: true, message: "外协负责人联系方式不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    // 监听appId变化
    appId(newVal) {
      if (newVal) {
        this.queryParams.id = newVal;
        this.handleQuery(); // 自动触发查询
      }
    }
  },
  created() {
    this.queryParams.id = this.appId;
    this.getList();
    this.getDeptTree();
  },
  methods: {
    appFlash() {
      this._isToto = this._isToto;
      if(this._isTodo === 0){
        this.reset(this.queryParams);
        this.queryParams.id  = null;
      }
      this.getList();
    },

    /** 查询临时通行证申请单列表 */
    getList() {
      this.loading = true;
      console.log("分页参数:", this.queryParams);
      listApplication(this.queryParams).then(response => {
        // console.log("分页响应:", response.data);
        this.applicationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查看人员按钮操作 */
    handleViewPerson(row) {
      // 触发父组件事件，传递申请单信息
      // console.log("查看人员", row.id);
      getApplication(row.id).then( response => {
        this.queryParams.appNo = response.data.appNo;
      })
      this.$emit('row-click', row);
    },

    /** 处理分页事件 */
    handlePagination(data) {
      // console.log("分页事件:", data);
      this.queryParams.pageNum = data.page;
      this.queryParams.pageSize = data.limit;
      this.getList();
    },
    handleGenerateQRCode(row){
      const appNo = row.appNo;
      const name = "张三";

      // 使用 axios
      axios({
        url: `/dev-api/api/apply/createQRCode?name=${name}&appNo=${appNo}`,
        method: 'GET',
        responseType: 'blob', // 重要！告诉axios接收二进制数据
      }).then(response => {
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `${name}.jpg`);
        document.body.appendChild(link);
        link.click();
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      }).catch(error => {
        console.error('下载失败:', error);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        appNo: undefined,
        appUid: undefined,
        appUnit: undefined,
        appPerson: undefined,
        entryCount: undefined,
        outUserName: undefined,
        outContact: undefined,
        content: undefined,
        appDate: undefined,
        outUid: undefined,
        outUnit: undefined,
        area: undefined,
        outPhone: undefined,
        status: undefined,
        createTime: undefined,
        updateTime: undefined,
        createBy: undefined,
        updateBy: undefined,
        remark: undefined
      };
      this.resetForm("form");
      this._isTodo = 0;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      console.log("重置")
      this.resetForm("queryForm");
      this.queryParams.id = null;
      this.queryParams.appNo = null;
      this._isTodo = 0;
      this.handleQuery();
    },
    // 多选框选中数据 - 增加状态判断
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      // 只有当所有选中项都是新建或已拒绝状态时才不禁用批量操作
      this.multiple = !selection.length

      // 检查所有选中的项是否都处于可送审状态（0-新建 或 3-已拒绝）
      if (selection.length === 0) {
        // 没有选中任何项时禁用
        this.multiple_2 = true
      } else {
        // 检查是否所有选中项的状态都是0或3
        this.multiple_2 = !selection.every(item => [0, 3].includes(item.status))
      }
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.loading = true;
      this.reset();
      this.isDetailView = true; // 设置为详情视图模式
      const id = row.id || this.ids
      getApplication(id).then(response => {
        console.log("详情响应:", response.data)
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "临时通行证申请单";
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 检查是否存在状态为新建的申请单
      const hasNewApplication = this.applicationList.some(item => item.status === 0 || item.status === '0' || item.status === '新建');

      if (hasNewApplication) {
        // 提示用户确认是否继续新增
        this.$modal.confirm('您已新建申请单，是否再次新建？').then(() => {
          // 用户点击确认，继续新增流程
          this.proceedToAdd();
        }).catch(() => {
          // 用户点击取消，不执行任何操作
          console.log('用户取消新增');
        });
      } else {
        // 没有新建的申请单，直接执行新增流程
        this.proceedToAdd();
      }
    },

    /** 执行新增操作 */
    proceedToAdd() {
      this.reset();
      this.isDetailView = false;
      this.open = true;
      this.title = "添加临时通行证申请单";
      getInfo().then(response => {
        this.form.outUserName = response.data.user.userName;
        this.form.outUnit = response.data.user.dept.deptName;
        this.form.outContact = response.data.user.nickName;
        this.form.outPhone = response.data.user.phonenumber;
      })
      generateAppNo().then(response => {
        console.log("申请单编号:", response.data)
        this.form.appNo = response.data;
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.isDetailView = false; // 设置为编辑模式
      const id = row.id || this.ids
      getApplication(id).then(response => {
        this.loading = false;
        this.form = response.data;
        console.log("修改响应:", response.data)
        this.open = true;
        this.title = "修改临时通行证申请单";
      });
    },
    handleSubmissionForReview(row) {
      this.loading = true;
      this.reset();
      this.isDetailView = false;

      // 处理单条还是批量
      const ids = row && row.id ? [row.id] : this.ids;

      sendOaToApproval(ids).then(response => {
        // 批量更新状态
        batchUpdateApprovalStatus(ids, 1).then(() => {
          this.$modal.msgSuccess("送審成功");
          this.getList();
        });
      }).catch(error => {
        this.$modal.msgError("送审失败: " + error.message);
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateApplication(this.form.id, this.form).then(response => {
              if(this.isDetailView ===  false){
                this.$modal.msgSuccess("修改成功");
              }
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            getDeptName(this.form.appUid).then(response => {
              console.log("deptName",response)
              this.form.appUnit = response.msg;
              addApplication(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const ids = row.id || this.ids;
      const ids = row?.id ? [row.id] : this.ids;
      this.$modal.confirm('是否确认删除临时通行证申请单编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delApplication(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('api/apply/export', {
        ...this.queryParams
      }, `申请单_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>

</style>
